#!/bin/bash
#
# Copyright 2015-2017 Adrian DC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# === ROM Automatic Releaser ===
function romautorelease()
{
  # Usage
  local function_usage='Usage: romautorelease <device_name> <rom_tag> [nowipe,j1/j2] (Advanced automated ROM builder)';
  local function_roms='ROM: <aosp> / <lineage> / <lx> / <master> / <next> / <sodp> / <caf> / <rr>';
  if [ -z "${1}" ] || [ -z "${2}" ]; then
    echo '';
    echo " ${function_usage}";
    echo "   ${function_roms}";
    echo '';
    return;
  fi;

  # Error with ANDROID_DEV_DRIVE missing
  if [ -z "${ANDROID_DEV_DRIVE}" ]; then
    echo '';
    echo ' Error: ANDROID_DEV_DRIVE is missing.';
    echo '  Please read the README.md from this project...';
    echo '';
    return;
  fi;

  # Variables
  local rom_device=${1};
  local rom_name=${2};
  local rom_params=${3};
  local cwd;
  local rom_logs;
  local rom_phone;
  local rom_target;
  local rom_tag;
  local rom_upload;

  # Logs path handling
  rom_logs=${ANDROID_DEV_DRIVE}/Logs;
  mkdir -p "${rom_logs}";

  # ==========================================================
  # Access ROM root
  cwd=$(pwd);
  croot;

  # ROM variables
  rom_phone=${rom_device^};
  rom_target=${rom_device};

  # ==========================================================
  # Select ROM target
  case "${rom_name}" in

    # AOSP 8.x
    aosp)
      rom_tag='AOSP-8.x';
      rom_upload="${rom_phone}/${rom_tag}";;

    # LineageOS 15.0
    lineage)
      rom_tag='LineageOS-15.x';
      rom_upload="${rom_phone}/${rom_tag}";;

    # AOSP-CAF 8.x
    caf)
      rom_tag='AOSP-CAF-8.x';
      rom_upload="${rom_phone}/${rom_tag}";;

    # LegacyXperia 15.0
    lx)
      rom_tag='LineageOS-15.x';
      rom_upload="LegacyXperia/${rom_device}/${rom_tag}";;

    # AOSP Master
    master)
      rom_tag='AOSP-Master';
      rom_upload='Development';;

    # LineageOS Next
    next)
      rom_tag='LineageNext-Master';
      rom_upload='Development';;

    # ResurrectionRemix Oreo
    rr)
      rom_tag='ResurrectionRemix-O';
      rom_upload="${rom_phone}/${rom_tag}";;

    # Sony AOSP 8.0
    sodp)
      rom_tag='AOSP-8.x';
      rom_target=$(codenametotarget "${rom_device}");
      rom_upload=${rom_phone}/AOSP-7.x;

      # Handle Sony AOSP kernel build
      sonyaospkernelupdate "${rom_device}";;

    # Unknown ROM
    *)
      echo '';
      echo ' Error: ROM target has not been found...';
      echo " ${function_usage}";
      echo "   ${function_roms}";
      echo '';
      return;;

  esac;

  # ==========================================================
  # When option enabled, use private upload for bringups
  if shtools-builds-bringup-active; then
    rom_upload='private';
  fi;

  # When option enabled, use debuggable bootimages
  if shtools-builds-debug-active; then
    bootimagedebuggable "${rom_target}" true;
    export WITH_SU=true;
  fi;

  # When option enabled, not local and not bringup, clean device out folder
  if (shtools-builds-clean-active || shtools-builds-cleandevices-active) &&
      ! shtools-builds-local-active && ! shtools-builds-bringup-active; then
    repodevclean;

  # Delete the devices relevant results
  elif [[ ! "${rom_params}" == *'nowipe'* ]]; then
    outdevcl "${rom_target}";
  fi;

  # When option enabled, clean RAM before build
  if shtools-builds-cleanram-active; then
    cleanrambuild;
  fi;

  # Compilation logs
  rom_logs_output=${rom_logs}/Build.${rom_device}.${rom_tag}.log;

  # ==========================================================
  # Build Android
  case "${rom_name}" in

    # AOSP Release | AOSP Master | Sony SODP
    aosp|master|sodp)
      source ./build/envsetup.sh;
      lunch "aosp_${rom_target}-userdebug";
      makes otapackage | tee "${rom_logs_output}";;

    # LineageOS Release | Lineage Next | LegacyXperia
    lineage|next|lx)
      repos "${rom_target}";
      brunch "${rom_target}" | tee "${rom_logs_output}";;

    # AOSP-CAF Release
    caf)
      source ./build/envsetup.sh;
      lunch "aospcaf_${rom_target}-userdebug";
      makes otapackage | tee "${rom_logs_output}";;

    # ResurrectionRemix Release
    rr)
      export RR_BUILDTYPE=OFFICIAL;
      repos "${rom_target}";
      brunch "${rom_target}" | tee "${rom_logs_output}";;

    # Unknown ROM
    *)
      ;;

  esac;

  # ==========================================================
  # When option enabled, use debuggable bootimages
  if shtools-builds-debug-active; then
    bootimagedebuggable "${rom_target}" false;
    export WITH_SU=;
  fi;

  # Notify build result
  pushbrom "${rom_device}" "${rom_tag}";

  # ==========================================================
  # Upload ROM when not working locally
  if ! shtools-builds-local-active; then
    devuplrom "${rom_device}" "${rom_upload}";
    if [ ! -z "${ANDROID_DEVELOPMENT_SHELL_TOOLS_UPLOADED_FILE}" ]; then
      pushb "$(hostname): ${rom_tag} for ${rom_device} uploaded";
    fi;
  fi;

  # ==========================================================
  # When option enabled, not local and not bringup, clean device out folder
  if (shtools-builds-clean-active || shtools-builds-cleandevices-active) &&
      ! shtools-builds-local-active && ! shtools-builds-bringup-active; then
    repodevclean;
  fi;

  # When option enabled, clean RAM after build
  if shtools-builds-cleanram-active; then
    cleanrambuild;
  fi;

  # Restore original path
  cd "${cwd}";
}

# === ROM Auto Releasers Menu ===
function autorelease()
{
  # Usage: autorelease (Helper menu access to autorelease* functions)

  # Variables
  local cnt=0;
  local key;
  local line_function;
  local line_usage;
  local list_functions=('');

  # Display shtools* menu
  echo '';
  for line_function in $(typeset -F | grep ' autorelease' | cut -d' ' -f 3 | grep -v '^autorelease$'); do

    # Parse usage
    line_usage=$(grep -a "Usage: ${line_function} " "${ANDROID_DEVELOPMENT_SHELL_TOOLS_SOURCES[@]}");
    if [ -z "${line_usage}" ]; then
      continue;
    fi;
    line_usage=${line_usage#*\(};
    line_usage=${line_usage%\)*};
    list_functions+=("${line_function}");

    # Item choice
    cnt=$((cnt + 1));
    echo -e "  \e[1;33m${cnt}: \e[1;37m${line_function} \e[1;32m[${line_usage}]\e[0m";

  done;
  echo '';

  # Request user input
  echo -n " > Command to run [1-${cnt}] : ";
  read -r key;

  # Execute requested function
  ${list_functions[${key}]} "${@}";
}

# === ROM Automated Builder Helper ===
function autobuild()
{
  # Usage
  if [ -z "${1}" ]; then
    echo '';
    echo ' Usage: autobuild <device> (Development automated ROM builder)';
    echo '';
    return;
  fi;

  # Variables
  local time_start;

  # Cleanup device outputs
  outdevcl "${1}";

  # Prepare device and 'brunch' environment
  repos "${1}";

  # Build device for Lineage
  if type brunch >/dev/null 2>&1; then
    time_start=$(date +%s);
    brunch "${1}";
    __maketimestring 'brunch' "${?}" "${time_start}";

  # Build device for AOSP
  else
    makes otapackage;
  fi;

  # Notify the build through Pushbullet
  pushb "${BUILD_RESULT}\n\n$(date)" 2>/dev/null;
}
